package com.iotechn.unimall.app.api.article;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dobbinsoft.fw.core.exception.AdminServiceException;
import com.dobbinsoft.fw.core.exception.ServiceException;
import com.dobbinsoft.fw.support.model.Page;
import com.iotechn.unimall.data.domain.ArticleClassDO;
import com.iotechn.unimall.data.domain.ArticleDO;
import com.iotechn.unimall.data.enums.ArticleType;
import com.iotechn.unimall.data.exception.ExceptionDefinition;
import com.iotechn.unimall.data.mapper.ArticleClassMapper;
import com.iotechn.unimall.data.mapper.ArticleMapper;
import com.iotechn.unimall.data.vo.AppArticleDetailVO;
import com.iotechn.unimall.data.vo.ArticleVO;
import com.iotechn.unimall.data.vo.SelectVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("appArticle")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleDO> implements ArticleService {

    @Resource
    private ArticleClassMapper articleClassMapper;

    @Override
    public Page<ArticleVO> articlePage(Integer page, Integer limit, Long articleClassId) throws ServiceException {
        QueryWrapper<ArticleDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ArticleDO::getArticleClassId, articleClassId);
        //已发布的
        wrapper.lambda().eq(ArticleDO::getStatus, ArticleType.HAVE_PUBLISHED.getCode());
        wrapper.lambda().ne(ArticleDO::getIsDelete, 1);
        wrapper.lambda().orderByDesc(ArticleDO::getHeat);
        return baseMapper.pageAppArticle(Page.div(page, limit, ArticleVO.class), wrapper);
    }


    @Override
    public AppArticleDetailVO detail(Long articleId, Long userId) throws ServiceException {
        QueryWrapper<ArticleDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ArticleDO::getId, articleId);
        ArticleDO articleDO = baseMapper.selectOne(wrapper);

        //热度加1
        articleDO.setHeat(articleDO.getHeat() + 1L);
        if (baseMapper.updateById(articleDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        AppArticleDetailVO appArticleDetailVO = new AppArticleDetailVO();
        BeanUtil.copyProperties(articleDO, appArticleDetailVO);
        return appArticleDetailVO;
    }

    @Override
    public List<SelectVO> articleType(Long userId) throws ServiceException {
        List<ArticleClassDO> articleClassDOS = articleClassMapper.selectList(null);
        List<SelectVO> collect = articleClassDOS.stream().map(o -> {
            SelectVO selectVO = new SelectVO();
            BeanUtil.copyProperties(o, selectVO);
            return selectVO;
        }).collect(Collectors.toList());
        return collect;
    }

}
